#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <netdb.h>

#define BUFLEN 2048
#define SERVER_IP "www.baidu.com"
#define SERVER_PORT 80

int main()
{
	int iSockFd = -1;
	struct sockaddr_in stServerAddr;
	struct hostent *pstHostent;

	int iRecvdNum = 0;
	char acSendBuf[BUFLEN] = {0};
	char acRecvBuf[BUFLEN] = {0};
	char acTemp[BUFSIZ] = {0};

	
	sprintf(acSendBuf, "GET / HTTP/1.0\r\n");

	strcat(acSendBuf, "Host: ");
	strcat(acSendBuf, SERVER_IP);
	strcat(acSendBuf, "\r\n");

	strcat(acSendBuf, "Accept: */*\r\n");
	strcat(acSendBuf, "Accept-Encoding: gzip,deflate,sdch\r\n");
	strcat(acSendBuf, "Accept-Language: zh-cn\r\n");

	strcat(acSendBuf, "Connection: Keep-Alive\r\n");

	strcat(acSendBuf, "\r\n\r\n");

	printf("acSendBuf:\n%s\n", acSendBuf);

	iSockFd = socket(AF_INET, SOCK_STREAM, 0);	
	if(iSockFd < 0) {
		printf("socket error\n");
		return -1;
	}

	pstHostent = gethostbyname(SERVER_IP);

	memset(&stServerAddr, 0, sizeof(stServerAddr));
	stServerAddr.sin_addr.s_addr = *((unsigned long*)pstHostent->h_addr);
	stServerAddr.sin_family = AF_INET;
	stServerAddr.sin_port = htons(SERVER_PORT);

	if(connect(iSockFd, (struct sockaddr *)&stServerAddr, sizeof(stServerAddr)) < 0) {
	printf("connect error\n");
		return -1;
	}

	write(iSockFd, acSendBuf, strlen(acSendBuf));

	while ((iRecvdNum = read(iSockFd, acRecvBuf, BUFLEN)) > 0)
	{
		acRecvBuf[iRecvdNum] = '\0';
		fputs(acRecvBuf, stdout);
	}

	if(iRecvdNum < 0) {
		printf("read error\n");
	}

	printf("*******************************\n");
	printf("acRecvBuf:\n%s\n", acRecvBuf);

	return 0;
}
